/*
 * Copyright (C) 2012 The Aliyunos Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.way.filemanager.providers;


import android.app.SearchManager;
import android.content.Intent;
import android.content.SearchRecentSuggestionsProvider;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.util.Log;

import com.way.filemanager.util.CommonFunc;
import com.way.filemanager.util.FileHelper;

/**
 * A content provider for manage the user search history.
 */
public class RecentSearchesContentProvider extends
        SearchRecentSuggestionsProvider {
    private static final String QUERY_WHERE_ORDER_BY_FULLPATH = "createtime DESC";
    private static final String TAG = "RecentSearchesContentProvider";
    private static final String[] SEARCH_SUGGESTIONS_BASED_ON_NAME_COLUMNS = {
        "_id",
        SearchManager.SUGGEST_COLUMN_TEXT_1, //1
        SearchManager.SUGGEST_COLUMN_TEXT_2, //2
        SearchManager.SUGGEST_COLUMN_ICON_1, //3
        SearchManager.SUGGEST_COLUMN_ICON_2,//4
        SearchManager.SUGGEST_COLUMN_INTENT_DATA,   //5
        SearchManager.SUGGEST_COLUMN_INTENT_ACTION, //6
        SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,   //7
        SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID,//8
        SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA,//9
        SearchManager.SUGGEST_COLUMN_TEXT_2_URL,  //10
        };
    /**
     * The authority string name.
     */
    public static final String AUTHORITY = "com.way.filemanager.providers.recentsearches"; //$NON-NLS-1$

    /**
     * The provider mode.
     */
    public static final int MODE = DATABASE_MODE_QUERIES;

    /**
     * Constructor of <code>RecentSearchesContentProvider</code>.
     */
    public RecentSearchesContentProvider() {
        super();
        setupSuggestions(AUTHORITY, MODE);
    }
    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
            Log.v(TAG, "query uri:" + uri.toString());
            FileListSQLiteOpenHelper mSqliteOpenHelper = new FileListSQLiteOpenHelper(this.getContext());
            if((mSqliteOpenHelper == null)||(selectionArgs.length < 1))
            {
                return null;
            }
            //mDb = mSqliteOpenHelper.getReadableDatabase();

            //columnNames = new ;
            MatrixCursor tmp = new MatrixCursor(SEARCH_SUGGESTIONS_BASED_ON_NAME_COLUMNS);
            String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);
            Log.v(TAG, "query limit:" + Integer.parseInt(limit));
            String selectWhere = null;
            /*try {
                selectWhere = new String(selectionArgs[0].getBytes(),"UTF8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.v(TAG, "UnsupportedEncodingException:"+e.toString());
            }*/
            selectWhere = selectionArgs[0];
            Cursor lstCursorFromDb = mSqliteOpenHelper.query(null, selectWhere,  Integer.parseInt(limit), QUERY_WHERE_ORDER_BY_FULLPATH,true);

            int IndexId = lstCursorFromDb.getColumnIndex(FileListSQLiteOpenHelper.QUERY_COLUMNS[0]);
            int Indexpath = lstCursorFromDb.getColumnIndex(FileListSQLiteOpenHelper.QUERY_COLUMNS[1]);
            int Indexfullpath = lstCursorFromDb.getColumnIndex(FileListSQLiteOpenHelper.QUERY_COLUMNS[2]);
            int Indextype_mime = lstCursorFromDb.getColumnIndex(FileListSQLiteOpenHelper.QUERY_COLUMNS[3]);
            int Indexfilename = lstCursorFromDb.getColumnIndex(FileListSQLiteOpenHelper.QUERY_COLUMNS[4]);
            int CreateTime = lstCursorFromDb.getColumnIndex(FileListSQLiteOpenHelper.QUERY_COLUMNS[5]);
            Log.v(TAG, "query IndexId:" + IndexId);
            Log.v(TAG, "query Indexpath:" + Indexpath);
            Log.v(TAG, "query Indexfullpath:" + Indexfullpath);
            Log.v(TAG, "query Indextype_mime:" + Indextype_mime);
            Log.v(TAG, "query limit:" + Indexfilename);
            Log.v(TAG, "query lstCursorFromDb.getCount:" + lstCursorFromDb.getCount());
            lstCursorFromDb.moveToPrevious();
            try{
            while(lstCursorFromDb.moveToNext())
            {
                Object[] rowContent = new Object[SEARCH_SUGGESTIONS_BASED_ON_NAME_COLUMNS.length];
                rowContent[0] = lstCursorFromDb.getInt(IndexId);
                rowContent[1] = lstCursorFromDb.getString(Indexfilename);//text 1
                rowContent[2] = CommonFunc.CreateTimeFormat_second(lstCursorFromDb.getLong(CreateTime));//text 2
                String fullpath = lstCursorFromDb.getString(Indexfullpath);
                int type = CommonFunc.getFileType(fullpath);
                Uri iconUri = CommonFunc.ParseAppUriRes(this.getContext(),type,FileHelper.getExtension(fullpath));


                if(iconUri != null)
                    rowContent[3] = iconUri;//icon 1
                else
                    rowContent[3] = getIcon(null);//icon 1
                rowContent[4] = null;//icon 2
                rowContent[5] = fullpath;//action data
                rowContent[6] = Intent.ACTION_VIEW;//action
                //rowContent[10] = Uri.fromFile(new File(fullpath));//url
                //lstCursorFromDb.getInt(IndexId);
                tmp.addRow(rowContent);
            }
            }finally{
                lstCursorFromDb.close();
            }

            //tmp = super.query(uri, projection, selection, selectionArgs, sortOrder);
            return tmp;

    }
    int getIcon(String mimetype)
    {
        return 0x7e05005c;
    }
}
